package test.work.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import test.work.vo.Student;

public class StudentDao implements InterfaceDao<Student> {
	private ArrayList<Student> lists;//Student ArrayList 생성
	private final String FILE="studentDB.data";//저장될 파일
	
	@Override
	public void insertItem(Student item) {
		if(!lists.contains(item)){
			lists.add(item);//추가
		}
	}

	@Override
	public void deleteItem(Student item) {
		if(lists.contains(item)){
			lists.remove(item);//삭제
		}
	}

	@Override
	public void updateItem(Student item) {
		if(lists.contains(item)){
			lists.set(lists.indexOf(item), item);//수정
		}
	}

	@Override
	public Student searchItem(Student item) {
		Student searchStudent=null;
		if(lists.contains(item)){
			searchStudent=lists.get(lists.indexOf(item));//가져오기
		}
		return searchStudent;
	}

	@Override
	public void prnItemList(Comparator<Student> comp) {
		if(comp!=null)
			Collections.sort(lists, comp);//정렬
		else
			Collections.sort(lists);
		
		for (Student std : lists) {
			System.out.println(std);
		}
	}

	@Override
	public void loadFile(){//파일 읽기
		ObjectInputStream ois = null;
		try {
			ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE)));
			lists= (ArrayList<Student>) ois.readObject();
		} catch (FileNotFoundException e) {
				try {
					new File(FILE).createNewFile();
					lists = new ArrayList<>();
				} catch (IOException e1) {}							
		}catch(Exception e){}
		finally{
			if(ois!=null)try {ois.close();} catch (IOException e) {}
		}
	}

	@Override
	public void saveFile(){//파일 쓰기
		ObjectOutputStream oos=null;
			try {
				oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE)));
				oos.writeObject(lists);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {}
			finally{
				if(oos!=null)try {oos.close();} catch (IOException e) {}	
			}			
	}
}
